package handlers

import (
	"encoding/json"
	"fmt"
	"restaurant-system/config"
	"restaurant-system/internal/models"
	"restaurant-system/internal/services"

	"github.com/gin-gonic/gin"
)

type DishRequest struct {
	Name        string   `json:"name" binding:"required"`
	Price       float64  `json:"price" binding:"required"`
	Description string   `json:"description"`
	Category    string   `json:"category" binding:"required"`
	ImageURL    string   `json:"image_url"`
	Stock       int      `json:"stock"`
	Tags        []string `json:"tags"`
}

// 创建菜品
func CreateDish(c *gin.Context) {
	var req DishRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Printf("绑定JSON失败: %v\n", err)
		fmt.Printf("请求体: %v\n", c.Request.Body)
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 将标签数组转换为JSON字符串
	tagsJSON, err := json.Marshal(req.Tags)
	if err != nil {
		fmt.Printf("转换标签失败: %v\n", err)
		c.JSON(500, gin.H{"error": "处理标签失败"})
		return
	}

	dish := models.Dish{
		Name:        req.Name,
		Price:       req.Price,
		Description: req.Description,
		Category:    req.Category,
		ImageURL:    req.ImageURL,
		Stock:       req.Stock,
		Status:      "available",
		Tags:        string(tagsJSON),
	}

	if err := config.DB.Create(&dish).Error; err != nil {
		fmt.Printf("创建菜品失败: %v\n", err)
		c.JSON(500, gin.H{"error": "创建菜品失败"})
		return
	}

	c.JSON(200, gin.H{"message": "创建菜品成功", "dish": dish})
}

// 更新菜品
func UpdateDish(c *gin.Context) {
	id := c.Param("id")
	var req DishRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	tagsJSON, _ := json.Marshal(req.Tags)

	updates := models.Dish{
		Name:        req.Name,
		Price:       req.Price,
		Description: req.Description,
		Category:    req.Category,
		ImageURL:    req.ImageURL,
		Stock:       req.Stock,
		Tags:        string(tagsJSON),
	}

	if err := config.DB.Model(&models.Dish{}).Where("id = ?", id).Updates(updates).Error; err != nil {
		c.JSON(500, gin.H{"error": "更新菜品失败"})
		return
	}

	c.JSON(200, gin.H{"message": "更新菜品成功"})
}

// 获取菜品列表
type DishResponse struct {
	models.Dish
	Tags []string `json:"tags"`
}

func GetDishes(c *gin.Context) {
	category := c.Query("category")
	var dishes []models.Dish
	query := config.DB.Model(&models.Dish{})

	if category != "" {
		query = query.Where("category = ?", category)
	}

	if err := query.Find(&dishes).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取菜品列表失败"})
		return
	}

	var response []DishResponse
	for _, dish := range dishes {
		var tags []string
		json.Unmarshal([]byte(dish.Tags), &tags)
		response = append(response, DishResponse{
			Dish: dish,
			Tags: tags,
		})
	}

	c.JSON(200, gin.H{"dishes": response})
}

// 获取单个菜品
func GetDish(c *gin.Context) {
	id := c.Param("id")
	var dish models.Dish

	if err := config.DB.First(&dish, id).Error; err != nil {
		c.JSON(404, gin.H{"error": "菜品不存在"})
		return
	}

	var tags []string
	json.Unmarshal([]byte(dish.Tags), &tags)
	response := DishResponse{
		Dish: dish,
		Tags: tags,
	}

	c.JSON(200, gin.H{"dish": response})
}

// 删除菜品
func DeleteDish(c *gin.Context) {
	id := c.Param("id")

	if err := config.DB.Delete(&models.Dish{}, id).Error; err != nil {
		c.JSON(500, gin.H{"error": "删除菜品失败"})
		return
	}

	c.JSON(200, gin.H{"message": "删除菜品成功"})
}

// 获取推荐菜品
func GetRecommendedDishes(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(401, gin.H{"error": "未登录"})
		return
	}

	dishes, err := services.GetRecommendedDishes(userID.(uint))
	if err != nil {
		c.JSON(500, gin.H{"error": "获取推荐菜品失败"})
		return
	}

	c.JSON(200, gin.H{"dishes": dishes})
}

// 获取热门菜品
func GetPopularDishes(c *gin.Context) {
	var popularDishes []models.Dish

	// 使用索引优化查询
	if err := config.DB.
		Select("dishes.*, SUM(order_items.quantity) as total_quantity").
		Joins("JOIN order_items ON order_items.dish_id = dishes.id").
		Where("dishes.status = ?", "available"). // 仅查询可用菜品
		Group("dishes.id").
		Order("total_quantity DESC").
		Limit(10).
		Find(&popularDishes).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取热门菜品失败"})
		return
	}

	c.JSON(200, gin.H{"dishes": popularDishes})
}
